#include <iostream.h>
#include <stdlib.h>
#include <iomanip.h>
#include "textlib.h"
//declaring the two functions walk and average
int walk(int distance);
double average(int numTries,int distance);
int main()
{
//the program was developped in a generic manner to handle n inputs for n
//operations.
int totDistance,ranWalks,distCovered=1;
//Prompting the user for input data.
cout<<" Enter the total distance to be covered: ";
cin>>totDistance;
cout<<endl;
cout<<" Enter the number of random walks : ";
cin>>ranWalks;
cout<<endl;
cout<<endl;
cout<<'\t'<<" Distance Interval"<<'\t'<<"Average "<<endl;
cout<<'\t'<<"__________________"<<'\t'<<"_______ "
<<endl<<endl;
//This loop will repeat the average calculations 10 times.
while (distCovered<=totDistance)
{
cout<<'\t'<<'\t'<<distCovered<<'\t'<<'\t'<<setreal(1,1)
<<average(ranWalks,distCovered)
<<endl<<endl;
distCovered++;
}
return 0;
}
//implementation of the walk function here!
int walk(int distance)
{
//the integer objects are initialized here!
int p=0,numSteps=0;
//this loop is active as long as the absolute value of p is less or equal to the
//distance!
while (abs(p)<distance)
{
//this if statement controls the heads and tails number of occurance.
//while a counter is active concurrently (numSteps) to yield the overall
//number of steps performed!
if ( rand() % 2 == 0)
p++;
else
p--;
numSteps++;
}
return numSteps;
}
//implementation of the average function here!
double average(int numTries, int distance)
{
double sumSteps=0,count=1;
//this will activate the loop as long as the counter is not equal to the
//number of tries.
while(count<=numTries)
{
//the sum is like a bin where the walk function results are accumulated
sumSteps+= double (walk(distance));
count++;
}
return (sumSteps/ count);
}
// Relationship between both distance and average are:
// average equal approx. distance^2.
//Run:
/*
Enter the total distance to be covered: 10
Enter the number of random walks : 50
Distance Interval Average
__________________ _______
1 1.0
2 4.0
3 10.2
4 16.5
5 25.6
6 34.2
7 48.9
8 73.7
9 86.4
10 99.7
Press any key to continue
*/
|